import React from "react";
import AMapLoader from "@amap/amap-jsapi-loader";
import { useEffect } from "react";
import { Button } from "antd";
import {areaAdd,areaGet} from '../../api/cake'
export default function Area() {
  let map = {}; //地图实例对象
  var polyEditor = {};
  var polygon
  useEffect(() => {
    AMapLoader.load({
      key: "326929be57e60ab4ae208dfbbf54063d", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ["AMap.PolygonEditor"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
      .then((AMap) => {
        map = new AMap.Map("container", {
          //设置地图容器id
          viewMode: "3D", //是否为3D地图模式
          zoom: 10, //初始化地图级别
          center: [106.55, 29.57], //初始化地图中心点位置
        });
        mapDraw(AMap);
      })
      .catch((e) => {
        console.log(e);
      });
  }, []);

  let mapDraw = (AMap) => {
    areaGet().then(res=>{
      console.log(res);
      let polyArr = []  //存放适量图对象
      res.data.results.forEach(item=>{
        let poly = new AMap.Polygon({ //创建矢量图对象
            path: item.path,
        });
        poly.on("dblclick", () => { //为矢量图对象绑定双击事件
          polyEditor.setTarget(poly);
          polyEditor.open();
        });
        polyArr.push(poly)
      })
      map.add(polyArr); //向地图对象绘制矢量图形
      map.setFitView();  //地图视图自动跳转到有矢量图的位置
      polyEditor.addAdsorbPolygons(polyArr);  //编辑矢量图
    })

    polyEditor = new AMap.PolygonEditor(map); //创建矢量图编辑对象
    polyEditor.on("add", function (data) { //新增矢量图
      console.log(data);
      polygon = data.target; //新的矢量图对象
      polyEditor.addAdsorbPolygons(polygon);
      polygon.on("dblclick", () => {
        polyEditor.setTarget(polygon);
        polyEditor.open();
      });
    });
  };

  function createPolygon() {
    polyEditor.close();
    polyEditor.setTarget();
    polyEditor.open();
  }

  let handleDone = ()=>{  //向数据库存储矢量图数据
    let path = polygon.getPath()  //获取新建的矢量图数据
    console.log(path);
    let arr = []
    path.forEach(({lng,lat})=>{ //将矢量图数据整合为二位数组
      arr.push([lng,lat])
    })
    areaAdd({ 
      city:'重庆市',
      path:arr
    })
  }
  return (
    <div>
      <Button type="primary" onClick={createPolygon}>
        新建范围
      </Button>
      <Button onClick={handleDone}>确认范围</Button>
      <div
        id="container"
        style={{ height: "500px", border: "1px solid red" }}
      ></div>
    </div>
  );
}
